package io.github.talelin.sleeve.controller.v1;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.github.talelin.sleeve.bo.FileBO;
import io.github.talelin.sleeve.common.api.vo.Result;
import io.github.talelin.sleeve.common.utills.ExcelHandler;
import io.github.talelin.sleeve.common.utills.ExcelListener;
import io.github.talelin.sleeve.common.utills.ExcelVerifier;
import io.github.talelin.sleeve.service.FileTestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api("文件接口")
@Slf4j
@RestController
@RequestMapping("file")
public class FileController {


    @Resource
    private FileTestService fileTestService;
    @Resource
    private ExcelVerifier excelVerifier;
    @Resource
    private ExcelListener excelListener;

    /**
     * @Description: Excel 文件导出 数据库表名
     */
    @ApiOperation("excel文件导出")
    @GetMapping("/export/{tableName}")
    public void excelExport(@PathVariable(name = "tableName") String tableName, HttpServletResponse response) throws IOException {
        List<List<String>> excelData = fileTestService.generateHead(tableName);
        try {
            String fileName = URLEncoder.encode(tableName, "UTF-8").replaceAll("\\+", "%20");
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = fileTestService.handlerStyleWrite();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream()).head(excelData)
                    .registerWriteHandler(new ExcelHandler())
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .sheet("模板").doWrite(null);
        } catch (Exception e) {
            e.printStackTrace();
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    /**
     * @Description: Excel 文件导入
     */
    @ApiOperation("excel文件导入")
    @PostMapping("/import")
    public Result<?> excelImport(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException, JSONException {
        Result<JSONObject> result = new Result<>();
        JSONObject data = new JSONObject();
        String fileName = file.getOriginalFilename();
        excelVerifier.setFileName(fileName);
        long start = System.currentTimeMillis();
        EasyExcel.read(file.getInputStream(), excelVerifier).sheet().doRead();
        long checkEnd = System.currentTimeMillis();
        if (excelVerifier.getCheckFlag() == 0) {
            data.put("takeUp", ((checkEnd - start) + "ms"));
            data.put("dataNum", excelVerifier.getDataNum());
            data.put("successNum", excelVerifier.getSuccessNum());
            data.put("failureNum", excelVerifier.getFailureNum());
            data.put("failDataList", excelVerifier.getFailDataList());
            result.setSuccess(false);
            result.setMessage("校验失败");
            result.setResult(data);
            return result;
        }
        excelListener.setFileName(fileName);
        EasyExcel.read(file.getInputStream(), excelListener).sheet().doRead();
        long importEnd = System.currentTimeMillis();
        data.put("takeUp", ((importEnd - start) + "ms"));
        data.put("dataNum", excelListener.getDataNum());
        data.put("successNum", excelListener.getSuccessNum());
        data.put("failureNum", excelListener.getFailureNum());
        data.put("failDataList", excelListener.getFailDataList());
        result.setSuccess(true);
        result.setMessage("请求成功");
        result.setResult(data);
        return result;
    }

    /**
     * @Description: 文件上传
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public List<FileBO> upload(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request) {
        MultipartHttpServletRequest multipartHttpServletRequest = ((MultipartHttpServletRequest) request);
        MultiValueMap<String, MultipartFile> fileMap = multipartHttpServletRequest.getMultiFileMap();
        List<FileBO> files = fileTestService.upload(fileMap);
        return files;
    }

    @GetMapping("/test")
    public void test() {
        fileTestService.generateHead("banner");
    }
}
